﻿var gMap = null;
var changedState = true;
var loadedFirstReport = false;

$(document).ready(function () {
    gMap = new GoogleMapClass({
        divTag: 'map-canvas',
        center: new google.maps.LatLng(15.120011, 108.808937),
        zoom: 8
    });

    $(".contentTabScroll .dropdown ul li a").on("click", function () {
        var link = $(this);
        var layerName = link.attr("layerName");
        var arrayFeature = model.arrayStoredFeature[layerName];
        if (typeof arrayFeature != "undefined") {
            var idObject = link.attr("keyObject");
            $.each(arrayFeature, function (index, object) {
                if (object.getProperty("id") == idObject) {
                    showMapPopup(object);
                }
            });
        }
    });

    gMap.init(function () {
        var len = model.LayerConfig.length;
        model.arrayStoredFeature = {};

        //Add each layer to map
        for (var i = 0; i < len; i++) {
            var config = model.LayerConfig[i];
            addDataLayer(model[config.Key], config.ImageUrl, config.Key);
        }

        //Setup the switch layer function 
        //For all
        $("#checkAllLayer").on("change", function () {
            var isVisible = $(this).prop("checked");
            $.each($(".switchLayer"), function (index, option) {
                $(option).prop("checked", isVisible);
                showHideLayer($(option).val(), isVisible);
            });
        });

        //For each layer
        $(".switchLayer").on("change", function () {
            var featureVisible = $(this).prop("checked");
            $("#checkAllLayer").prop("checked", $(".switchLayer:checkbox:checked").length == $(".switchLayer").length);
            showHideLayer($(this).val(), featureVisible);
        });

        //Add TOC control to map
        gMap.addControl(document.getElementById("TableOfContent"), google.maps.ControlPosition.TOP_RIGHT);

        //Handle on clicking each feature on map
        gMap.handleClickOnDataLayer(function (evt) {
            showMapPopup(evt.feature);
        });

        //Handle on draging completely on map
        gMap.handleDragEndOnMap(function () {
            //Get current bounnd on map
            var bounds = gMap.getMap().getBounds();
            var maxLat;
            var minLat;
            var maxLng;
            var minLng;

            //Set the max and min Lat
            if (bounds.getNorthEast().lat() < bounds.getSouthWest().lat()) {
                maxLat = bounds.getSouthWest().lat();
                minLat = bounds.getNorthEast().lat();
            } else {
                maxLat = bounds.getNorthEast().lat();
                minLat = bounds.getSouthWest().lat();
            }

            //Set the max and min Lng
            if (bounds.getNorthEast().lng() < bounds.getSouthWest().lng()) {
                maxLng = bounds.getSouthWest().lng();
                minLng = bounds.getNorthEast().lng();
            } else {
                maxLng = bounds.getNorthEast().lng();
                minLng = bounds.getSouthWest().lng();
            }

            var dataToSend = { bound: { MaxLat: maxLat, MinLat: minLat, MaxLng: maxLng, MinLng: minLng} };
            Helpers.ajaxHelper.ajax({
                type: "POST",
                controller: "Map",
                action: "ReloadDataOnEndDrag",
                showMask: false,
                dataType: 'html',
                contentType: 'application/json; charset=utf8',
                data: JSON.stringify(dataToSend),
                success: function () {

                }
            });
        });

        //Empty Comment
        gMap.DrawingTools();

        //Put handler for event on switch tab
        setSwitchTabsMenuEvent();

        $("#btnViewReport").on("click", function () {
            var data = {};

            data.SampleIds = [];
            $.each($("input.sampleCheckBox:checked"), function (index, object) {
                data.SampleIds[index] = $(object).val();
            });

            data.SourceIds = [];
            $.each($("input.areaCheckedBox:checked"), function (index, object) {
                data.SourceIds[index] = $(object).val();
            });

            data.ParamIds = [];
            var paramArrayIndex = 0;
            $.each($("#dropDownMaterial :checkbox:checked"), function (index, object) {
                if (index != 0) {
                    data.ParamIds[paramArrayIndex++] = $(object).val();
                }
            });

            data.StandardId = $("#selectedStandards").val();
            data.BeginTime = $("#beginDateTimePicker").val();
            data.EndTime = $("#endDateTimePicker").val();
            data.TimeByMonth = $("input[type='radio'][name='selectTime']:checked").val();
            data.AggerateFunction = $("input[type='radio'][name='selectAgg']:checked").val();

            var dataToSend = { dataModel: data };
            //Call clear function on server side
            Helpers.ajaxHelper.ajax({
                type: "POST",
                controller: "Map",
                action: "GetStaticTable",
                showMask: false,
                dataType: 'html',
                contentType: 'application/json; charset=utf8',
                data: JSON.stringify(dataToSend),
                success: function () {
                }
            });

        });
    });
});

//Handle on loading the report configuration
function loadReportConfig() {
    $("#selectMaterial").dropdownchecklist({
        onItemClick: function() {
        },
        width: 200,
        firstItemChecksAll: true
    });


    //Handle for all checked of sample
    //**Handle when checking all checkbox
    $("#allSampleCheckBox").on("change", function () {
        //Handle on sample
        var checkedInput = $(this).prop("checked");
        $.each($(".sampleCheckBox"), function (index, object) {
            $(object).prop("checked", checkedInput);
        });
        
        //Handle on area
        var displayValue = (checkedInput == true) ? "table-row" : "none";
        $("#allAreaCheckBox").prop("checked", checkedInput);
        $.each($(".AreaRow"), function (index, object) {
            $(object).css("display", displayValue);
            $(object).find(".areaCheckedBox").prop("checked", checkedInput);
        });
        
        fillMaterialData();
    });
    
    //**Handle when checking each checkbox
    $(".sampleCheckBox").on("change", function() {
        var displayClass = "";
        var selectedValueNum = 0;
        
        //Get the selected class values 
        $.each($(".sampleCheckBox"), function(index, object) {
            if ($(object).prop("checked")) 
            {
                displayClass += $(object).val() + " ";
                selectedValueNum++;
            }
        });
        
        //display or hide rows by the selected values
        displayClass = $.trim(displayClass);
        $.each($(".AreaRow"), function(index, object) {
            if (CheckClasses(displayClass,$(object))) 
            {
                $(object).css("display", "table-row");
                $(object).find(".areaCheckedBox").prop("checked", true);
            } 
            else 
            {
                $(object).css("display", "none");
                $(object).find(".areaCheckedBox").prop("checked", false);
            }
        });

        //set check or uncheck all
        $("#allSampleCheckBox").prop("checked", $(".sampleCheckBox").length == selectedValueNum);
        
        fillMaterialData();
    });


    //Handle for all checked of area
    //**
    $("#allAreaCheckBox").on("change", function () {
        var checkedInput = $(this).prop("checked");
        $.each($(".areaCheckedBox"), function (index, object) {
            if ($(".AreaRow").eq(index).css("display") != "none") {
                $(object).prop("checked", checkedInput);
            }
        });

        fillMaterialData();
    });
    
    //**
    $(".areaCheckedBox").on("change", function () {
        fillMaterialData();
    });

    //Create datepicker on report
    $("#beginDateTimePicker").datepicker({ dateFormat: "mm-yy" });
    $("#endDateTimePicker").datepicker({ dateFormat: "mm-yy" });
}

//Handle display the data for material dropbox
function fillMaterialData() {
    var displayClassArea = "";
    var selectedValueNum = 0;

    //Get the selected class values 
    $.each($(".areaCheckedBox"), function (index, object) {
        if ($(object).prop("checked")) {
            displayClassArea += $(object).val() + " ";
            selectedValueNum++;
        }
    });

    displayClassArea = $.trim(displayClassArea);
    $.each($("#dropDownMaterial .ui-dropdownchecklist-item"), function (index, object) {
        if (index != 0) {
            var currentOption = $("#selectMaterial").find("option:eq(" + index + ")");
            if (CheckClasses(displayClassArea, currentOption)) {
                $(object).css("display", "block");
            } else {
                $(object).css("display", "none");
            }
        }
    });

    //set check or uncheck all
    $("#allAreaCheckBox").prop("checked", $(".areaCheckedBox").length == selectedValueNum);
}

//Handle on switch tab
function setSwitchTabsMenuEvent() {
    $(".tabs a").on("click", function() {
        var module = $(this).text();
        if (module == "Báo cáo") {
            $("#reportContent").css("display", "block");
            $("#mapContent").css("display", "none");
            //On showing the report at the first
            if (!loadedFirstReport) {
                loadReportConfig();
                loadedFirstReport = true;
            }
        } else {
            $("#reportContent").css("display", "none");
            $("#mapContent").css("display", "block");
        }
    });
}

//Add the new layer (include the image and key name of that layer) to the data layer of google map
function addDataLayer(data, imageUrl, key) {
    model.arrayStoredFeature[key] = new Array();
    for (var x in data) {
        var d = data[x];
        var lon = d.Lon;
        var lat = d.Lat;
        var point;
        if (lon == null ||
            lat == null) {
            point = gMap.getCenterMap();
        } else {
            point = new google.maps.LatLng(lat, lon);
        }

        var feature = new google.maps.Data.Feature({
            id: key + "_" + d.Id,
            geometry: point,
            properties: {
                id: d.Id,
                mappedTable: d.MappedTable
            }
        });
        model.arrayStoredFeature[key][x] = feature;
        gMap.addFeature(feature);
        gMap.overrideFeatureStyle(feature, {
            icon: imageUrl
        });
    }
}

//Create the chart from the datatable
function createChart(datatable, options) {
    changedState = false;
    var titleChart = "";
    var categoriesChart = [];
    var measureValueSeriesChart = {
        name: 'Giá trị đo',
        color: 'rgba(186,60,61,.9)',
        data: [],
        pointPadding: 0.4,
        pointPlacement: 0
    };
    var standardValueSeriesChart = {
        name: 'QCVN',
        color: 'rgba(248,161,63,0.5)',
        data: [],
        pointPadding: 0.2,
        pointPlacement: 0
    };

    var index = 0;
    $("#" + datatable + " tr").each(function(i, tr) {
        if (i > 0) {
            if (options[i].checked == true) {
                //Get series for axis X by the first cell of each row
                var cells = $(tr).find("td");
                categoriesChart[index] = $(cells[0]).text();

                //Get measure value to draw chart by the the second cell of each row
                var measureValue = $(cells[1]).text();
                if (measureValue.length > 0) {
                    measureValueSeriesChart.data[index] = parseFloat(measureValue);
                } else {
                    measureValueSeriesChart.data[index] = 0;
                }

                //Get standard value to draw chart by the the third cell of each row
                var standardValue = $(cells[2]).text();
                if (standardValue.length > 0) {
                    standardValueSeriesChart.data[index] = parseFloat(standardValue);
                } else {
                    standardValueSeriesChart.data[index] = 0;
                }
                index++;
            }
        }
    });

    //Create chart for popup
    $('#chart_container').highcharts({
        chart: {
            type: 'column'
        },
        title: {
            text: titleChart
        },
        xAxis: {
            categories: categoriesChart,
            labels: {
                rotation: -60
            }
        },
        yAxis: [{
            min: 0,
            title: {
                text: 'Giá trị'
            }
        }],
        legend: {
            shadow: false
        },
        tooltip: {
            shared: true
        },
        plotOptions: {
            column: {
                grouping: false,
                shadow: false,
                borderWidth: 0
            }
        },
        series: [measureValueSeriesChart,
            standardValueSeriesChart]
    });
}

//switch between show and hide status of each layer
function showHideLayer(layerKey, status) {
    $.each(model.arrayStoredFeature[layerKey], function(index, object) {
        gMap.overrideFeatureStyle(object, {
            visible: status
        });
    });
}

//show poup on map
function showMapPopup(feature) {
    var dataToSend = { id: feature.getProperty("id"), mappedTable: feature.getProperty("mappedTable") };
    var pos = feature.getGeometry().get();
    //Call clear function on server side
    Helpers.ajaxHelper.ajax({
        type: "POST",
        controller: "Map",
        action: "GetDataPopup",
        showMask: false,
        dataType: 'html',
        contentType: 'application/json; charset=utf8',
        data: JSON.stringify(dataToSend),
        success: function(result) {
            gMap.showMapPopup(result, pos);

            //Check if the datatable is exist
            if ($('#datatable').length > 0) {
                $('#datatable').on('init.dt', function() {
                    //Create check lits dropbox
                    $("#selectSource").dropdownchecklist({
                        onItemClick: function() {
                            changedState = true;
                        },
                        onComplete: function(selector) {
                            if (changedState) {
                                createChart("chartTable", $("#dropBoxContainer input:checkbox"));
                            }
                        },
                        width: 200,
                        firstItemChecksAll: true,
                        icon: {},
                        textFormatFunction: function(options) {
                            var selectedOptions = options.filter(":selected");
                            var countOfSelected = selectedOptions.size();
                            var size = options.size();
                            switch (countOfSelected) {
                            case 0:
                                return "Chưa chọn tiêu chuẩn";
                            case 1:
                                return selectedOptions.text();
                            case size:
                                return options.filter(":eq(0)").text();
                            default:
                                return "Chọn nhiều tiêu chuẩn";
                            }
                        }
                    });

                    $.each($("#dropBoxContainer input:checkbox"), function(index, object) {
                        $(object).prop("checked", true);
                    });

                    //Create chart for popup
                    createChart("chartTable", $("#dropBoxContainer input:checkbox"));

                    //Create tab for popup
                    $("#tabs").tabs({
                        show: { effect: "fadeIn", duration: 500 }
                    });
                });

                //Create table for popup
                $('#datatable').dataTable({
                    "paging": false,
                    "info": false,
                    "scrollY": "230px",
                    "scrollX": true,
                    "autoWidth": false,
                    "ordering": false
                });

            } else {
                $("#tabs").tabs({
                    show: { effect: "fadeIn", duration: 1000 }
                });
            }
        }
    });
}

//Check if element is belonged to the class
function CheckClasses(stringClassName, jqueryElement) {
    var classes = stringClassName.split(" ");
    var result = false;
    $.each(classes, function (index, s) {
        if (jqueryElement.hasClass(s)) {
            result = true;
        }
    });
    return result;
}